#include <time.h>
#include <stdio.h>

//#include "stdafx.h"
#include <stdarg.h>
#include <windows.h>

#include "DailyRecode.h"

DailyRecode* DailyRecode::s_hand = NULL;

void DailyRecode::init(const std::string& logPath) {
	_logPath = logPath;
	if (_logPath.at(_logPath.length() - 1) != '/') {
		_logPath += '/';
	}
}

void  DailyRecode::getTime( char str[], const int maxSize ) {
	time_t tt = time(NULL);
	tm t;
	localtime_s(&t, &tt);

	sprintf_s(str, maxSize, "%d-%d-%d-%d:%d:%d",
		t.tm_year + 1900, 
		t.tm_mon + 1,
		t.tm_mday, 
		t.tm_hour,
		t.tm_min,
		t.tm_sec);
}

bool DailyRecode::weirteToFile(const char* path, const  char* str) {
	FILE* file = NULL;
	fopen_s(&file, path, "a+");

	if (file == NULL) {
		return false;
	}
	char timeStr[1024] = { 0 };
	getTime(timeStr, 1024);
	fprintf_s(file, "%s:  %s\n", timeStr, str);
	fclose(file);

	return true;
}

DailyRecode* DailyRecode::getInst() {
	if (s_hand == NULL) {
		s_hand = new(DailyRecode);
	}
	return s_hand;
}

DailyRecode::DailyRecode() {
	 _recordInfo = false;
	 _recordWarn = false;
	 _recordErr= true;
	 _logPath = "./";
}

DailyRecode::~DailyRecode() {
}

void DailyRecode::setLevel(const bool recordInfo,
										const bool recordWarn,
										const bool recordErr) {
	_recordInfo = recordInfo;
	_recordWarn= recordWarn;
	_recordErr = recordErr;
}

void DailyRecode::logInfo(const char* format, ...) {
	const char* str1 = "Info.log";

	char str[1024] = { 0 };
	va_list args;
	va_start(args, format);
	vsprintf_s(str, 1024, format, args);
	va_end(args);
	printf_s("%s", str);

	weirteToFile(str1, str);
}

void DailyRecode::logErr(const char* format, ...) {
	const char* str1 = "Error.log";

	char str[1024] = { 0 };
	va_list args;
	va_start(args, format);
	vsprintf_s(str, 1024, format, args);
	va_end(args);
	printf_s("%s", str);

	weirteToFile(str1, str);
}

void DailyRecode::logWarn(const char* format, ...) {
	const char* str1 = "Wan.log";

	char str[1024] = { 0 };
	va_list args;
	va_start(args, format);
	vsprintf_s(str, 1024, format, args);
	va_end(args);
	printf_s("%s", str);

	weirteToFile(str1, str);
}
